package com.lagou.handler;

import com.lagou.RPCProvider;
import com.lagou.service.UserServiceImpl;
import com.lagou.service.po.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class UserServerHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
        if(msg.toString().startsWith("UserService")){
            UserServiceImpl userService = new UserServiceImpl();
            String result = userService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(result);
        } else if(msg instanceof RpcRequest) {
            //消息协议为RpcRequest
            RpcRequest rpcRequest = (RpcRequest) msg;
            RPCProvider rpcProvider = applicationContext.getBean("rpcProvider", RPCProvider.class);
            //创建动态代理对象
            Object proxy = rpcProvider.createProxy(rpcRequest);

            //反射调用
            String className = rpcRequest.getClassName();
            Class<?> aClass = Class.forName(className);
            Method declaredMethod = aClass.getDeclaredMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
            Object result = declaredMethod.invoke(proxy, rpcRequest.getParameters());

            //返回调用结果
            ctx.writeAndFlush(result.toString());
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
